/*
 * CManagerMtr.cpp
 *
 *  Created on: 2017-2-4
 *      Author: root
 */

#include"CManagerMtr.h"
#include"PublicLog.h"
#include"PublicMySql.h"
#if USE_THREAD_MANAGER&&USE_PUBLIC_MTR
CManagerMtr g_managermtr;
CManagerMtr::CManagerMtr(){
#if    USE_PUBLIC_MYSQL
    m_mysqltype=MYSQL_BASE;
    memset(m_databasename,0,sizeof(m_databasename));
    memset(m_tablename,0,sizeof(m_tablename));
#endif
}
CManagerMtr::~CManagerMtr(){

}
void CManagerMtr::RunOnce(){
    SETIPLIST tmplist;
    m_Mutex.Lock();
    m_worklist.clear();
    tmplist=m_waitlist;
    m_worklist=m_waitlist;
    m_waitlist.clear();
    m_Mutex.UnLock();
    if(tmplist.empty()==false){
		MAPSTRINGLIST result=GetMtrInfo(tmplist,5);
		UpLoadMtrResult(result);
    }else{
		sleep(5);
    }
}
void CManagerMtr::InsertIPList(SETIPLIST iplist){
    if(m_thread.IsAllThreadsRunning()==false)return;
    m_Mutex.Lock();
    SETIPLIST::iterator it=iplist.begin();
    while(it!=iplist.end()){
		if(m_worklist.find(it->c_str())==m_worklist.end()&&
			m_waitlist.find(it->c_str())==m_waitlist.end()){
			m_waitlist.insert(it->c_str());
        }
		it++;
    }
    m_Mutex.UnLock();
}
void CManagerMtr::SetMysqlInfo(int type,const char*db,const char*table){
#if    USE_PUBLIC_MYSQL
    m_mysqltype=type;
    strcpy(m_databasename,db);
    strcpy(m_tablename,table);
#endif
}
void CManagerMtr::UpLoadMtrResult(MAPSTRINGLIST result){
    if(result.empty())return;
#if    USE_PUBLIC_MYSQL
    char headstr[1024]={0};
    sprintf(headstr,"INSERT INTO `%s`.`%s`(`ip`,`mtr_info`,`mtr_time`)VALUES",m_databasename,m_tablename);
    const char*endstr="ON DUPLICATE KEY UPDATE `mtr_info`=VALUES(`mtr_info`),`mtr_time`=VALUES(`mtr_time`);";
    int Count=0;
    std::string str="";
    MYSQL*mysql=OpenMySQL(m_mysqltype);
    if(mysql==NULL){
		WRONG("数据库连接失败跳过本次上传");
		return;
    }
    MAPSTRINGLIST::iterator it=result.begin();
    while(it!=result.end()){
		if(Count==0){
			str=headstr;
		}else{
			str+=",";
        }
		char Data[10240]={0};
		sprintf(Data,"('%s','%s',UNIX_TIMESTAMP())",
              it->first.c_str(),it->second.c_str());
		str+=Data;
		Count++;
		if(Count>100){
			str+=endstr;
			if(mysql)RunMySQL(mysql,str.c_str());
			Count=0;
        }
		it++;
    }
    if(Count>0){
		str+=endstr;
		if(mysql)RunMySQL(mysql,str.c_str());
		Count=0;
    }
    mysql=CloseMySQL(mysql);
    INFO("上传%zd条记录到数据库 ",result.size());
#endif
}
#endif
